#define _CRT_SECURE_NO_WARNINGS 1


#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

typedef char STDataType;

typedef struct stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

void STInit(ST* ps)
{
	assert(ps);

	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

void STDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

bool STEmpty(ST* ps)
{
	assert(ps);

	return 0 == ps->top;
}

int STSize(ST* ps)
{
	assert(ps);

	return ps->top;
}

void STPush(ST* ps, STDataType x)
{
	assert(ps);

	if (ps->capacity == ps->top)
	{
		int newcapacity = 0 == ps->capacity ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapacity);

		if (NULL == tmp)
		{
			perror("realloc fail");
			return;
		}

		ps->a = tmp;
		ps->capacity = newcapacity;
	}

	ps->a[ps->top] = x;
	ps->top++;
}

void STPop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	ps->top--;
}

STDataType STTop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	return ps->a[ps->top - 1];
}


bool isValid(char* s)
{
	ST st;
	STInit(&st);

	while (*s)
	{
		if (('(' == *s) || ('[' == *s) || ('{' == *s))
		{
			STPush(&st, *s);
		}
		else
		{
			//右括号比左括号多
			if (STEmpty(&st))
			{
				STDestroy(&st);
				return false;
			}

			//左右括号不匹配
			char top = STTop(&st);
			STPop(&st);

			if (('(' == top && *s != ')')
				|| ('[' == top && *s != ']')
				|| ('{' == top && *s != '}'))
			{
				STDestroy(&st);
				return false;
			}
		}

		s++;
	}

	bool ret = STEmpty(&st);
	STDestroy(&st);
	return ret;
}